package zzxkj.blog.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import zzxkj.blog.WorkingException.NotFoundException;
import zzxkj.blog.config.RabbitConfig;
import zzxkj.blog.dto.AdminSearchParam;
import zzxkj.blog.dto.BlogQuery;
import zzxkj.blog.dto.ShowBlog;
import zzxkj.blog.pojo.Blog;
import zzxkj.blog.pojo.User;
import zzxkj.blog.search.mq.entity.EsMessage;
import zzxkj.blog.service.BlogService;
import zzxkj.blog.service.TagService;
import zzxkj.blog.service.TypeService;
import zzxkj.blog.utils.MyBeanUtil;
import zzxkj.blog.utils.RedisUtil;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;


/**
 * @author zzxkj
 */
@Slf4j
@Controller
@RequestMapping("/admin")
public class BlogController {
    private final BlogService blogService;
    private final TypeService typeService;
    private final TagService tagService;
    private final AmqpTemplate amqpTemplate;
    private final RedisUtil redisUtil;

    public BlogController(BlogService blogService, TypeService typeService, TagService tagService, AmqpTemplate amqpTemplate, RedisUtil redisUtil) {
        this.blogService = blogService;
        this.typeService = typeService;
        this.tagService = tagService;
        this.amqpTemplate = amqpTemplate;
        this.redisUtil = redisUtil;
    }

    /**
     * pagehelper 必须先声明分页
     * 页面初始化
     * @param param
     * @param model
     * @return
     */
    @GetMapping("/blogs")
    public String blogs(AdminSearchParam param, Model model) {
        log.info("pram:{}", param);
        int size = 8;
        String sort = "update_time"+" ASC";
        PageHelper.startPage(param.getPage(), size);
        List<BlogQuery> Blogs = blogService.getAllBlog(param);
        PageInfo<BlogQuery> page = new PageInfo<>(Blogs);
        log.info("page:{}", page);
        model.addAttribute("types", typeService.getAllTypeAndBlog());
        model.addAttribute("page", page);
        return "admin/blogs";
    }
    /**
     * //@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum
     * 搜索请求只更新列表
     * @param param
     * @param model
     * @return
     */
    @PostMapping("/blogs/search")
    public String search(AdminSearchParam param, Model model) {
        log.info("search_pram:{}", param);
        int size = 8;
        String sort = "update_time"+" DESC";
        PageHelper.startPage(param.getPage(), size);
        List<BlogQuery> Blogs = blogService.getAllBlog(param);
        PageInfo<BlogQuery> page = new PageInfo<>(Blogs);
        log.info("search_page:{}", page);
        model.addAttribute("page", page);
        return "admin/blogs :: blogList";
    }

    /**
     * 博客详情
     * @param model
     * @return
     */
    @GetMapping("/blogs/input")
    public String input(Model model) {
        model.addAttribute("types", typeService.getAllTypeAndBlog());
        model.addAttribute("tags", tagService.getAllTagAndBlog());
        model.addAttribute("blog", new Blog());
        return "admin/blogs-input";
    }

    /**
     * 编辑博客
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/blogs/{id}/input")
    public String editInput(@PathVariable Long id, Model model) {
        model.addAttribute("types", typeService.getAllTypeAndBlog());
        model.addAttribute("tags", tagService.getAllTagAndBlog());
        ShowBlog blog = blogService.getBlogById(id);
        blog.init(tagService.getTagsByBlogId(id));
        model.addAttribute("blog", blog);
        return "admin/blogs-input";
    }

    /**
     * 保存博客
     * @param blog
     * @param redirectAttributes
     * @param session
     * @return
     */
    @PostMapping("/blogs")
    public String post(Blog blog, RedirectAttributes redirectAttributes, HttpSession session) {
        log.info("前端接收到的blog={}",blog);
        blog.setUser((User) session.getAttribute("user"));
        //设置blog的type
        blog.setType(typeService.getType(blog.getType().getId()));
        //设置blog中typeId属性
        blog.setTypeId(blog.getType().getId());
        //给blog中的List<Tag>赋值
        blog.setTags(tagService.getTagByString(blog.getTagIds()));
        //设置用户id
        blog.setUserId(blog.getUser().getId());
        int ret;
        if (blog.getFlag() == null || "".equals(blog.getFlag())) {
            blog.setFlag("原创");
        }
        if (blog.getId() == null) {
            ret = blogService.saveBlog(blog);
        } else {
             ShowBlog b = blogService.getBlogById(blog.getId());
             if (b == null) {
                 throw new NotFoundException("震惊！！！本不该存在该博客！！！！");
             }
             BeanUtils.copyProperties(blog, b, MyBeanUtil.getNullPropertyNames(blog));
             blog.setUpdateTime(new Date());
             //更新DB
             ret = blogService.updateBlog(blog);
             //删除缓存
             String key = "blog:" + blog.getId();
             if(redisUtil.hasKey(key)){
                 redisUtil.del(key);
             }
        }
        if (ret == 0) {
            redirectAttributes.addFlashAttribute("message", "操作失败");
        } else {
            //mq异步通知es
            amqpTemplate.convertAndSend(RabbitConfig.common_exchange,RabbitConfig.es_bind_key,
                    new EsMessage(blog.getId(), EsMessage.CREATE_OR_UPDATE));
            redirectAttributes.addFlashAttribute("message", "操作成功");
        }
        return "redirect:/admin/blogs";
    }

    /**
     * 删除博客
     * @param id
     * @param redirectAttributes
     * @return
     */
    @GetMapping("/blogs/{id}/delete")
    public String delete(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        blogService.deleteBlog(id);
        amqpTemplate.convertAndSend(RabbitConfig.common_exchange,RabbitConfig.es_bind_key,
                new EsMessage(id, EsMessage.REMOVE));
        redirectAttributes.addFlashAttribute("message", "删除成功");
        return "redirect:/admin/blogs";
    }


}
